package com.heavenbird.book.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.heavenbird.book.BookConst;
import com.heavenbird.common.BaseAction;

public class LoginFilter implements Filter {
	private static transient Log log = LogFactory.getLog(LoginFilter.class);
	private String[] excludedURLS;
	
	public void destroy() {
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		String currentURL = request.getRequestURI();
		String url = currentURL.substring(currentURL.indexOf("/", 1), currentURL.length());
		
		boolean allowedRequest = false;
		
		for(int i = 0;i < excludedURLS.length; i++) {
			if(url.equals(excludedURLS[i])) {
				allowedRequest = true;
				break;
			}
		}
		
		if(!allowedRequest) {
			HttpSession httpSession = request.getSession();
			if (httpSession == null || httpSession.getAttribute(BookConst.COMMON.SESSION_USER_ID) == null) {
				response.sendRedirect(request.getContextPath() + "/login.html");
				return;
			}
		}
		chain.doFilter(request, response);
	}

	public void init(FilterConfig config) throws ServletException {
		String excludedURL = config.getInitParameter("excluded");
		if(log.isDebugEnabled()) {
			log.debug(excludedURL);
		}
		if(StringUtils.isNotBlank(excludedURL)) {
			excludedURLS = StringUtils.split(excludedURL, ";");
		}
	}

}
